package dao;

import model.Admin;

import java.sql.*;
import java.util.List;

public class Dao {
    private static String dbClassName = "com.mysql.cj.jdbc.Driver";
    private static String dbUrl = "jdbc:mysql://localhost:3306/new_sunny";
    private static String dbUser = "root";
    private static String dbPwd = "20020816+-YCY";

    private static Connection conn = null;

    /* 构造方法， 获取连接 */
    Dao()
    {
        try
        {
            if (conn==null)
            {
                Class.forName(dbClassName); //注册驱动程序
                conn = DriverManager.getConnection(dbUrl,dbUser,dbPwd);
            }
            else return;
        }

        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    /* 关闭连接 */
    public static void close()
    {
        try
        {
            if (conn != null) conn.close();

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally {

            conn = null;
        }
    }

    public static ResultSet executeQuery(String sql)
    {
        try{
            if(conn == null)  new Dao();
            return conn.createStatement().executeQuery(sql);
        }
        catch (Exception E)
        {
            E.printStackTrace();
            return null;
        }
    }

    // 修改
    public static int exeUpdate(String sql)
    {
        try{
            if(conn == null) new Dao();
            return conn.createStatement().executeUpdate(sql);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return -1;
        }

    }

    public static Admin check(String name, String password)
    {
        int i = 0;

        Admin operator = new Admin();
        String sql = "select * from admin where username = '" + name + "' and password = '" + password + "' and id = 1";
        try{
            ResultSet rs = Dao.executeQuery(sql);
            assert rs != null;
            if(rs.next())
            {
                operator.setId(rs.getInt("id"));
                operator.setName(rs.getString("username"));
                operator.setPassword(rs.getString("password"));
            }

            else return null;
        } catch (Exception e){
            e.printStackTrace();
        }
        Dao.close();

        return operator;
    }
}
